/*
 * Copyright 2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.seppiko.chart.utils;

import com.d_project.qrcode.ErrorCorrectionLevel;
import com.d_project.qrcode.GIFImage;
import com.d_project.qrcode.QRCode;

import com.google.zxing.qrcode.encoder.ByteMatrix;

/**
 * D_Project util
 *
 * @author Leonard Woo
 */
public class DProjectUtil {

  public static QRCode getQRCode(String text, int typeNumber, int errorCorrectionLevel) {
    if (typeNumber == 0) {
      return QRCode.getMinimumQRCode(text, errorCorrectionLevel);

    } else {
      QRCode qr = new QRCode();
      qr.setTypeNumber(typeNumber);
      qr.setErrorCorrectionLevel(errorCorrectionLevel);
      qr.addData(text);
      qr.make();

      return qr;
    }
  }

  public static int parseErrorCorrectionLevel(String ecl) {
    if ("L".equalsIgnoreCase(ecl) ) {
      return ErrorCorrectionLevel.L;
    } else if ("Q".equalsIgnoreCase(ecl) ) {
      return ErrorCorrectionLevel.Q;
    } else if ("M".equalsIgnoreCase(ecl) ) {
      return ErrorCorrectionLevel.M;
    } else if ("H".equalsIgnoreCase(ecl) ) {
      return ErrorCorrectionLevel.H;
    } else {
      throw new IllegalArgumentException("invalid error correct level : " + ecl);
    }
  }

  public static GIFImage createGIFImage(QRCode qrcode, int cellSize, int margin){
    int imageSize = qrcode.getModuleCount() * cellSize + margin * 2;
    GIFImage image = new GIFImage(imageSize, imageSize);
    for (int y = 0; y < imageSize; y++) {
      for (int x = 0; x < imageSize; x++) {
        if (margin <= x && x < imageSize - margin
            && margin <= y && y < imageSize - margin) {
          int col = (x - margin) / cellSize;
          int row = (y - margin) / cellSize;
          if (qrcode.isDark(row, col) ) {
            image.setPixel(x, y, 0);
          } else {
            image.setPixel(x, y, 1);
          }
        } else {
          image.setPixel(x, y, 1);
        }
      }
    }

    return image;
  }

  public static ByteMatrix convertToZxingByteMatrix(QRCode qrcode) {
    ByteMatrix output = new ByteMatrix(qrcode.getModuleCount(), qrcode.getModuleCount());
    for (int row = 0; row < qrcode.getModuleCount(); row++) {
      for (int col = 0; col < qrcode.getModuleCount(); col++) {
        if (qrcode.isDark(row, col)) {
          output.set(col, row, 1);
        }
      }
    }
    return output;
  }

}
